package ducpham.rogueconsole.mark2;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;

public class CharacterSpriteCanvas extends ASpriteCanvas implements
		ITileGenerator {

	private static final Color DEFAULT_CHAR_COLOR = new Color(0x268bd2);
	private int width;
	private int height;
	private Font font;
	private FontRenderContext frc = new FontRenderContext(null, true, true);

	public CharacterSpriteCanvas(Font font) {
		this.font = font;
		Image img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = (Graphics2D) img.getGraphics();

		width = (int) g.getFontMetrics(font).getMaxCharBounds(g).getWidth() + 6;
		height = (int) g.getFontMetrics(font).getMaxCharBounds(g).getHeight() + 6;
		
		g.dispose();
	}

	@Override
	public Image getSprite(String c) {
		if (c == null || c == "")
			c = " ";
		else
			c = String.valueOf(c.charAt(0));

		Image result = super.getSprite(c);

		if (result == null) {
			result = createNewCharSprite(c);
		}
		return result;
	}

	private Image createNewCharSprite(String c) {
		Image result = new BufferedImage(width, height * 2,
				BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = (Graphics2D) result.getGraphics();
		g.setColor(DEFAULT_CHAR_COLOR);

		TextLayout tl = new TextLayout(String.valueOf(c), font, frc);
		tl.draw(g, 3, height * 3 / 4 + 1);

		g.dispose();
		super.addSprite(c, result);
		return result;
	}
	
	@Override
	@Deprecated
	public Image addSprite(String desc, Image sprite) {
		super.addSprite(desc, sprite);
		return null;
	}

	@Override
	public ATile getNewTile(int row, int col) {
		return new ConsoleTile(row * width, col * height, this);
	}

	@Override
	public int getTileWidth() {
		return width;
	}

	@Override
	public int getTileHeight() {
		return height;
	}
}
